<?php

namespace Xin\ChatGPT\Channels\Zhipu;

use GuzzleHttp\Psr7\MultipartStream;
use Xin\ChatGPT\Channels\Concerns\Transportable;
use Xin\ChatGPT\Contracts\File as FileContract;
use Xin\ChatGPT\ResponseUtil;

class File implements FileContract
{
    use Transportable;

    public function lists()
    {
        $response = $this->transporter->get('files');
        $result = ResponseUtil::toArray($response);

        return $result['data'] ?? [];
    }

    public function upload($filePath, $purpose = null)
    {
        $purpose = $purpose ?: 'fine-tune';
        // 创建一个 MultipartStream 对象，它将用于包含文件数据
        $multipart = new MultipartStream([
            [
                'name' => 'file',
                'contents' => fopen($filePath, 'r+'),
            ],
            [
                'name' => 'purpose',
                'contents' => $purpose,
            ],
        ]);

        // 发送带有文件的 POST 请求
        $response = $this->transporter->post('files', [
            'body' => $multipart,
            'http_errors' => false,
        ]);
        $result = ResponseUtil::toArray($response);

        return $result['data'] ?? [];
    }

    public function delete($fileId)
    {
        $response = $this->transporter->delete("files/{$fileId}");
        $result = ResponseUtil::toArray($response);

        return $result['data'] ?? [];
    }

    public function retrieve($fileId)
    {
        $response = $this->transporter->get("files/{$fileId}");
        $result = ResponseUtil::toArray($response);

        return $result['data'] ?? [];
    }

    public function retrieveContent($fileId)
    {
        $response = $this->transporter->get("files/{$fileId}/content");
        $result = ResponseUtil::toArray($response);

        return $result['data'] ?? [];
    }
}
